<template>
  <div class="editor-container">
    <div
      class="header"
    >
      <div class="title">新建动态</div>
      <div>
        <el-button style="width: 120px;" @click="saveDynamic(editorText)">保存到草稿</el-button>
        <el-button style="width: 120px;" type="primary" plain @click="handlePreview">预览</el-button>
        <el-button style="width: 120px;" type="primary" @click="checkDynamic(editorText)">发送审核</el-button>
      </div>
    </div>
    <div class="previewDialog">
      <el-dialog
        :visible.sync="previewVisible"
        :show-close="false"
      >
        <Preview :preview-content="editorText" />
      </el-dialog>
    </div>
    <div v-if="status === '4' && editorText.error_message" class="fail-box">
      <div>
        <svg-icon icon-class="check-refuse" />
        &nbsp&nbsp审核不通过!</div>
      <ul>
        <li v-for="(item, index) in editorText.error_message" class="question">
          <div class="question-label">问题{{ index + 1 }}：</div>
          <div class="question-content">{{ item.message }}</div>
        </li>
      </ul>
      <div style="text-align: right;margin-top: 12px">
        客服电话： 400-826-6205
      </div>
    </div>
    <div class="content">
      <div class="sidebar">
        <div class="top">
          <div v-if="status===4" class="title">草稿箱(审核拒绝)</div>
          <div v-if="status===1" class="title">草稿箱(未发布)</div>
          <div v-if="!status" class="title">草稿箱</div>
          <el-button style="width:100%" icon="el-icon-plus" @click="handleAddDraft"/>
        </div>
        <ul :loading="loadingDraftList">
          <li
            v-for="(item, index) in draftList"
            :key="item.dynamic_id"
            :class="[activeIndex===index? 'active': '']"
            class="draft-list pointer"
          >
            <div
              class="draft-list-picture"
              @click="getDraftContent(item.dynamic_id, index)"
            >
              <img :src="item.forward_show_image" alt="封面" width="100%" height="100%">
            </div>
            <div
              class="draft-list-title"
              style="word-break: break-all;"
              @click="getDraftContent(item.dynamic_id, index)"
            >
              {{ item.title }}
            </div>
            <div class="btn-delete" @click="handleDeleteDraft(item.dynamic_id)">
              <i class="el-icon-delete"/>
            </div>
          </li>
        </ul>
      </div>
      <div :loading="loadingDraftContent" class="content-right">
        <div class="right-top">
          <div id="editor-toolbar" class="editor-toolbar"/>
          <div>
            <div class="editor-title">
              <textarea v-model="editorText.title" placeholder="请在这里输入标题" type="text" style="border: none; width: 100%; margin-right: 20px"/>
            </div>
            <div class="editor-author">
              <input v-model="editorText.author" placeholder="请在这里输入作者" type="text" style="border: none; width: 100%;">
            </div>
            <div id="editor-text" class="editor-text">
              <div>请在这里输入内容</div>
            </div>
          </div>
        </div>
        <div class="right-bottom">
          <div class="preview-picture pointer" >
            <img :src="imageUrl" alt="封面" width="100%" height="100%" @click="dialogVisible = true">
          </div>
          <div class="upload-picture">
            <div class="title">封面</div>
            <div class="upload-btn">
              <el-upload
                :limit="1"
                :file-list="fileList"
                :headers="{token: token}"
                :action="uploadUrl"
                :on-change="changeFile"
                :auto-upload="false"
                :on-remove="removeFile"
                name="upfile"
                class="upload-demo"
                multiple>
                <el-button size="small">从本地上传</el-button>
              </el-upload>
            </div>
            <div>
              <el-dialog
                :visible.sync="dialogVisible"
                :before-close="handleClose"
                title="裁切封面"
                width="864px">
                <Cropper :image="imageUrl" @previewImg="getImg"/>
                <span slot="footer" class="dialog-footer">
                  <el-button @click="dialogVisible = false">取 消</el-button>
                  <el-button type="primary" @click="dialogVisible = false">完成</el-button>
                </span>
              </el-dialog>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import Editor from 'wangeditor'
import Cropper from '@/components/Cropper/index.vue'
import Preview from '@/components/Preview'
import { getServiceDraftAllList, getOneDraftInfo, saveServiceDynamic, delServiceDynamic } from '@/api/dynamic'

export default {
  components: {
    Cropper, Preview
  },
  data() {
    return {
      token: this.$store.getters.token,
      previewVisible: false,
      draftList: [],
      questions: [],
      fileList: [],
      editorText: {
        status: 1,
        show_image: '',
        forward_show_image: '',
        title: '',
        author: '',
        content: '',
        dynamic_id: ''
      },
      storageText: null,
      editor: {},
      activeIndex: 0,
      loadingDialog: true,
      loadingDraftList: true,
      loadingDraftContent: false,
      timer: {},
      imageUrl: '',
      dialogVisible: false,
      status: this.$route.query.status,
      uploadUrl: process.env.BASE_API + '/service/files/uploadOneFile' // 图片上传网址
    }
  },
  created() {
    this.judgeStatus()
  },
  mounted() {
    this.createEditor()
    this.temporaryStorage()
  },
  destroyed() {
    this.cancelTimer()
  },
  methods: {
    // 判断状态请求数据
    judgeStatus() {
      if (this.$route.query.id) {
        const id = this.$route.query.id
        this.fetchServiceDraft(this.status, id)
        this.getDraftContent(id)
      } else {
        this.fetchServiceDraft(this.status)
        if (window.localStorage.editorText) {
          this.editorText = JSON.parse(window.localStorage.editorText)
          this.storageText = this.editorText.content
        }
      }
    },
    // 获取草稿列表
    fetchServiceDraft(status) {
      console.log('获取列表', status)
      this.loadingDraftList = true
      getServiceDraftAllList(status).then(response => {
        if (response.status === 200) {
          this.draftList = response.data
          this.loadingDraftList = false
        }
      })
    },
    // 获取草稿内容
    getDraftContent(id, index) {
      this.activeIndex = index
      if (id) {
        this.loadingDraftContent = true
        getOneDraftInfo(id).then(response => {
          if (response.status === 200) {
            this.editorText = response.data
            this.editor.txt.html(this.editorText.content)
            this.loadingDraftContent = false
          }
        })
      } else {
        this.editorText = this.emptyEditor
        this.editor.txt.html(this.editorText.content)
      }
    },
    // 创建富文本编辑器
    createEditor() {
      this.editor = new Editor('#editor-toolbar', '#editor-text')
      this.editor.customConfig.uploadImgShowBase64 = true // 使用 base64 保存图片
      this.editor.customConfig.onchange = (html) => {
        // html 即变化之后的内容
        this.editorText.content = html
      }
      this.editor.create()
      if (this.storageText) {
        this.editor.txt.html(this.editorText.content)
      }
    },
    // 定时保存草稿到localStorage
    temporaryStorage() {
      this.timer = setInterval(() => {
        if (window.localStorage) {
          window.localStorage.editorText = JSON.stringify(this.editorText)
        }
      }, 10000)
    },
    // 销毁定时保存
    cancelTimer() {
      clearInterval(this.timer)
    },
    // 增加草稿
    handleAddDraft() {
      const title = '标题'
      const draft = {
        title: title,
        show_imge: '',
        dynamic_id: ''
      }
      this.draftList.unshift(draft)
      this.emptyEditor()
      this.editor.txt.html(this.editorText.content)
    },
    // 预览草稿
    handlePreview() {
      this.previewVisible = true
    },
    // 删除草稿
    handleDeleteDraft(id) {
      this.$confirm('此操作将永久删除该草稿, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        delServiceDynamic(id).then(response => {
          if (response.status === 200) {
            this.fetchServiceDraft(this.status)
            this.emptyEditor()
            this.$message({
              type: 'success',
              message: '删除成功!'
            })
          } else {
            this.$message({
              type: 'error',
              message: '删除失败!'
            })
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    // 审核前验证
    _validateText(text) {
      return (text.show_image && text.title && text.author && text.content && text.forward_show_image)
    },

    // 发布审核
    checkDynamic(editorText) {
      editorText.status = 0
      if (this._validateText(editorText)) {
        saveServiceDynamic(editorText).then(response => {
          if (response.status === 200) {
            this.fetchServiceDraft(this.status)
            this.emptyEditor()
            this.$message({
              message: '发送审核成功',
              type: 'success'
            })
          } else {
            this.$message({
              message: '发送审核失败',
              type: 'error'
            })
          }
        })
      } else {
        if (!editorText.show_image) {
          this.$message({
            type: 'warning',
            message: '请裁切封面'
          })
        }
        if (!editorText.forward_show_image) {
          this.$message({
            type: 'warning',
            message: '请裁切转发封面'
          })
        }
        if (!editorText.content) {
          this.$message({
            type: 'warning',
            message: '请填写文章内容'
          })
        }
        if (!editorText.author) {
          this.$message({
            type: 'warning',
            message: '请填写文章作者'
          })
        }
        if (!editorText.title) {
          this.$message({
            type: 'warning',
            message: '请填写文章标题'
          })
        }
      }
    },
    // 保存到草稿
    saveDynamic(editorText) {
      editorText.status = 1
      saveServiceDynamic(editorText).then(response => {
        if (response.status === 200) {
          this.fetchServiceDraft(this.status)
          this.emptyEditor()
          this.$message({
            message: '动态已保存',
            type: 'success'
          })
        } else {
          this.$message({
            message: '动态保存失败',
            type: 'failure'
          })
        }
      })
    },
    changeFile(file, fileList) {
      var This = this
      // this.imageUrl = URL.createObjectURL(file.raw);
      var reader = new FileReader()
      reader.readAsDataURL(file.raw)
      reader.onload = function(e) {
        this.result // 这个就是base64编码了
        This.imageUrl = this.result
        setTimeout(() => {
          This.dialogVisible = true
        }, 300)
      }
    },
    // 清空数据
    emptyEditor() {
      this.fileList = []
      this.imageUrl = ''
      this.editorText.author = ''
      this.editorText.title = ''
      this.editorText.dynamic_id = ''
      this.editorText.show_image = ''
      this.editorText.forward_show_image = ''
      this.editorText.content = ''
      this.editorText.status = ''
      this.editor.txt.clear()
      window.localStorage.removeItem('editorText')
    },
    // 获得裁剪图片
    getImg(previewImg) {
      console.log('previewImg', previewImg)
      console.log(this.editorText)
      this.editorText.forward_show_image = previewImg.img1
      this.editorText.show_image = previewImg.img2
    },
    removeFile(file, fileList) {
      console.log('remove')
    },
    handleClose(done) {
      this.$confirm('确认关闭？')
        .then(_ => {
          done()
        })
        .catch(_ => {
        })
    }
  }
}
</script>
<style lang="scss">
  .previewDialog {
    .el-dialog {
      width: 428px;
      height: 857px;
      border-radius: 46px;
      margin-top: 2vh !important;
      background: url("../../assets/img/mobile-bg.png");
      .el-dialog__header {
        padding: 0;
      }
    }
    .el-dialog__body {
      overflow: hidden;
      border: none;
    }
    .el-dialog__headerbtn {
      top:0;
      right: 0;
    }
  }
  .w-e-text-container.editor-text {
    border: none !important;
    margin: 0 70px;
  }

  .w-e-menu {
    z-index: 0 !important;
  }
  .w-e-text {
    a {
      color: #3668ff;
      text-decoration-line: underline;
    }
    min-height: 260px;
    overflow-y: auto!important;
  }
  .el-dialog__body {
    border-top: 1px solid #d8d8d8;
    border-bottom: 1px solid #d8d8d8;
  }
</style>
<style rel="stylesheet" lang="scss" scoped>
  textarea:focus, input:focus {
    outline: none;
  }

  .active {
    background: rgba(242, 242, 242, 1);
  }

  .editor-container {
    display: flex;
    flex-direction: column;
    font-family: MicrosoftYaHei;
    padding: 30px;
    min-height: 100%;
  }

  .header {
    display: flex;
    margin-bottom: 30px;
    justify-content: space-between;
    .title {
      height: 40px;
      font-size: 20px;
      color: rgba(51, 51, 51, 1);
      line-height: 40px;
    }
  }

  .fail-box {
    margin-bottom: 20px;
    text-align: left;
    background: rgba(254, 241, 240, 1);
    border-radius: 2px;
    border: 1px solid rgba(250, 163, 158, 1);
    padding: 17px 24px;
    .question {
      display: flex;
      padding: 12px 26px 0 26px;
      .question-label {
        margin-right: 10px;
      }
    }
  }

  .draft-list-picture {
    width: 50px;
    height: 50px;
    flex-shrink: 0;
  }

  .draft-list-title {
    padding-left: 12px;
    width: 140px;
    height: 38px;
    font-size: 14px;
    color: rgba(51, 51, 51, 1);
    line-height: 19px;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
    overflow: hidden;
  }

  .content {
    background-color: #fff;
    display: flex;
    flex-grow: 1;
    min-height: calc(100vh - 200px);
    .sidebar {
      flex-shrink: 0;
      width: 250px;
      border-right: 1px solid #e9e9e9;
      .draft-list {
        display: flex;
        position: relative;
        padding: 10px 0 10px 20px;
        border-bottom: 1px solid #e9e9e9;
        .btn-delete {
          padding: 15px 20px;
          color: red;
        }
      }
      .top {
        padding: 20px 20px;
        border-bottom: 1px solid #E9E9E9;
        .title {
          padding-bottom: 33px;
          font-size: 16px;
          /*color: rgba(51, 51, 51, 1);*/
        }
      }
    }
    &-right {
      flex-grow: 1;
      display: flex;
      flex-direction: column;
      .right-top {
        background-color: #fff;
        flex-grow: 1;
        padding: 0 20px;
      }
      .right-bottom {
        height: 194px;
        display: flex;
        padding: 40px 100px;
        background: rgba(250, 250, 250, 1);
        border-top: 1px solid rgba(233, 233, 233, 1);
      }
    }
    .editor-title {
      padding: 40px 0 0 80px;
      textarea {
        font-size: 22px;
        color: rgba(153, 153, 153, 1);
        resize: none;
        overflow-y: visible;
      }
    }
    .editor-author {
      margin: 0 80px;
      padding-bottom: 18px;
      border-bottom: 1px solid rgba(233, 233, 233, 1);
      input {
        font-size: 16px;
        color: rgba(153, 153, 153, 1);
      }
    }
    .editor-toolbar {
      padding-bottom: 10px;
      padding-top: 10px;
      margin-top: 20px;
      z-index: 0 !important;
      background-image: linear-gradient(181deg, #FFFFFF 0%, #E9E9E9 100%);
      border-bottom: 1px solid #e9e9e9;
    }
    .editor-text {
      margin: 20px 70px 0 70px;
      min-height: 260px;
      /*min-height: calc(100vh - 670px);*/
      z-index: 0 !important;
      overflow-y: auto;
      font-size: 16px;
      color: rgba(153, 153, 153, 1);
      line-height: 19px;
    }
  }

  .preview-picture {
    width: 200px;
    height: 114px;
    background: rgba(238, 238, 238, 1);
    margin-right: 40px;
    flex-shrink: 0;
  }

  .upload-picture {
    .title {
      font-size: 14px;
      color: rgba(51, 51, 51, 1);
    }
    .upload-btn {
      margin-top: 14px;
    }
  }
</style>
